package edu.shiep.sunyu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;

import edu.shiep.sunyu.model.BusSchedule;
import edu.shiep.sunyu.model.DBClient;
import edu.shiep.sunyu.model.DBConstants;
import edu.shiep.sunyu.model.Database;
import edu.shiep.sunyu.model.Table;

public class BookingSelectBusServlet extends HttpServlet {

	private static final long serialVersionUID = -6227119382314173591L;
	
	private DBClient _client = null;
	
	public void init(ServletConfig config) throws ServletException {
	   super.init(config);
	   
	   _client = new DBClient();
	   if (!_client.connect()) {
		   System.out.println("Can't connect to database!!!");
	   }
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// reading the user input
		String bus_id = request.getParameter("bus_id");
		
		// Get bus time
		Database db = _client.getDB(DBConstants.Const_Database_Name);
		
		Table table = db.getTable(DBConstants.Const_Table_Bus_Schedule_Name);

		BasicDBObject query = new BasicDBObject();
		query.put(BusSchedule.Field_Id, bus_id);
		
		DBCursor cursor = table.query();
		
		List lstBusSchedule = new ArrayList();
		
		while (cursor.hasNext()) { 
        	BasicDBObject doc = (BasicDBObject)cursor.next();
        	BusSchedule bus = new BusSchedule();
        	bus.deserialize(doc);
        	
        	lstBusSchedule.add(bus.getId());
        	System.out.println(doc);
        }

		request.setAttribute("bus_id", bus_id);
		request.setAttribute("bus_schedule", lstBusSchedule);
		
		RequestDispatcher view = request.getRequestDispatcher("BookingSelectSchedule.jsp");
		view.forward(request, response);
	}  
	
}
